<?php
/*
 * Module Cover.
 * For saving static images
 * @author Andrey Muhin
 * @version 2.0 
 */

class Cover extends A_Content  {
	
	
	public function __get($param)
	{
		if ($param=="dir") {
			if (NULL === $dir = $this->_top->_config->content->cover_path) {
				throw $this->_top->Utils->PushError("Cover_path must be set in main ini file","Системная ошибка. Обратитесь к разработчикам");
			}
			return $this->_top->Utils->fixDirPath($dir);
		}  else {
			return false;
		}
		
	}
	
		
	/**
	 * Returns instance of SingleCover class
	 *
	 * @param Integer $id
	 * @return SingleCover
	 */
	public function getById($id) {
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleCover($this->_top,$this,$id);
		}
		
		return $this->_cashe_obj[$id];
	}
	
	public function add()
	{
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."cover(add_date,last_mod) VALUES(NOW(),NOW());");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}
	
}


class SingleCover extends A_SingleContent  {
	
	/**
	 * REturns pointer to Image object
	 *
	 * @var Image
	 */
	public $file;
	
	public function loader()
	{
		unset($this->file);
		
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."cover c WHERE cover_id={$this->_content_id}");
		if (count($get_data)==0)
			throw $this->_top->Utils->PushError("Cover Id: {$this->_content_id} not found","Системная ошибка. Обратитесь к администратору");
		else {
			$this->_data = $get_data[0];
		}
		return true;
	}
	
	public function __get($param)
	{
		if ($param=="file") {
			if ($this->file_name=="") {
				return false;
			}
			else {
				try {
					return $this->_top->Utils->Image($this->_parent->dir.$this->file_name);
				} catch (Exception $e) {
					return false;
				}
			}
		} elseif (isset($this->_data[$param])) {
			return $this->_data[$param];
		} else {
			return false;
		}
	}
	
	public function __set($param,$value) {
		if ($param=="file") {
				$param = "file_name";
				$value = $value->full_path;
		} 
		
		if ($param=="cover_id" || $param=="add_date" || !isset($this->_data[$param])) {
			return false;
		} else {
			if ($param=="file_name") {
				$img = $this->_top->Utils->Image($value);
				$img->name = "{$this->_content_id}.{$img->extention}";
				$img->Move($this->_parent->dir);
				$value = $img->name;
			}
			
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."cover SET `$param`='$value',last_mod=NOW() WHERE cover_id={$this->_content_id}");
		}
		return true;
	}
	
	
	
	protected function deleter() {
		if ($this->file!=false) {
			try {
				$this->file->delete();
			} catch (Exception $e) { 
				return false;
			}
		}
		
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."cover WHERE cover_id={$this->_content_id}");
		
		return true;
	}

	

}

?>